<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="120px"
    >
      <el-row>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-row>
      <el-form-item label="文件夹名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入文件夹名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="父文件夹id" prop="parentId">
        <el-input v-model="queryParams.parentId" placeholder="请输入父文件夹id" clearable size="small" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="显示顺序" prop="sort">
        <el-input v-model="queryParams.sort" placeholder="请输入显示顺序" clearable size="small" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="文件夹所有者id" prop="ownerUserId">
        <el-input v-model="queryParams.ownerUserId" placeholder="请输入文件夹所有者id" clearable size="small" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="文件夹状态（0正常 1停用）" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择文件夹状态（0正常 1停用）" clearable size="small">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="文件夹创建时间">
        <el-date-picker
          v-model="dateRangeFolderCreateTime"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="文件夹修改时间">
        <el-date-picker
          v-model="dateRangeFolderLastTime"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <!-- <el-form-item label="创建时间">
        <el-date-picker v-model="dateRangeCreateTime" size="small" style="width: 240px" value-format="yyyy-MM-dd"
                        type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item label="租户编号" prop="tenantId">
        <el-input v-model="queryParams.tenantId" placeholder="请输入租户编号" clearable size="small" @keyup.enter.native="handleQuery"/>
      </el-form-item> -->
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['xiaoBizHandler:XT-b-folder:create']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['xiaoBizHandler:XT-b-folder:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

  <!-- 树形列表 -->
  <el-table v-if="refreshTable" v-loading="loading" :data="list" row-key="id" :default-expand-all="isExpandAll"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
    <!-- 列表 -->
    <!-- <el-table v-loading="loading" :data="list"> -->
      <!-- <el-table-column label="文件夹id" align="center" prop="id" /> -->
      <el-table-column label="文件夹名称" align="left" prop="name" />
      <!-- <el-table-column label="父文件夹id" align="center" prop="parentId" /> -->
      <!-- <el-table-column label="显示顺序" align="center" prop="sort" /> -->
      <!-- <el-table-column label="文件夹所有者id" align="center" prop="ownerUserId" /> -->
      <!-- <el-table-column label="文件夹状态（0正常 1停用）" align="center" prop="status" /> -->
      <el-table-column
        label="文件夹创建时间"
        align="center"
        prop="folderCreateTime"
      />
      <el-table-column
        label="文件夹修改时间"
        align="center"
        prop="folderLastTime"
      />
      <!-- <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="租户编号" align="center" prop="tenantId" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['xiaoBizHandler:XT-b-folder:update']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['xiaoBizHandler:XT-b-folder:delete']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="文件夹名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入文件夹名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="父文件夹" prop="parentId">
              <treeselect v-model="form.parentId" :options="folderOptions" :normalizer="normalizer" placeholder="选择父文件夹" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="显示顺序" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入显示顺序" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-col :span="12">
          <el-form-item label="文件夹所有者id" prop="ownerUserId">
            <el-input
              v-model="form.ownerUserId"
              placeholder="请输入文件夹所有者id"
            />
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="12">
          <el-form-item label="文件夹状态（0正常 1停用）" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio label="1">请选择字典生成</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col> -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="文件夹创建时间" prop="folderCreateTime">
              <el-date-picker
                clearable
                size="small"
                v-model="form.folderCreateTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择文件夹创建时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件夹修改时间" prop="folderLastTime">
              <el-date-picker
                clearable
                size="small"
                v-model="form.folderLastTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择文件夹修改时间"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-col :span="12">
          <el-form-item label="租户编号" prop="tenantId">
            <el-input v-model="form.tenantId" placeholder="请输入租户编号" />
          </el-form-item>
        </el-col> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createXTbFolder,
  updateXTbFolder,
  deleteXTbFolder,
  getXTbFolder,
  listFolder,
  getXTbFolderPage,
  exportXTbFolderExcel,
} from "@/api/xiaoBizHandler/xTbFolder";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getNowDate } from "@/utils/ruoyi";

export default {
  name: "XTbFolder",
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件夹列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否展开，默认不展开，数据有点多，默认不展开
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 文件夹选项
      folderOptions:[],
      // 是否显示弹出层
      open: false,
      dateRangeFolderCreateTime: [],
      dateRangeFolderLastTime: [],
      dateRangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        name: null,
        parentId: null,
        sort: null,
        ownerUserId: null,
        status: null,
        tenantId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "文件夹名称不能为空", trigger: "blur" },
        ],
        // parentId: [
        //   { required: true, message: "父文件夹id不能为空", trigger: "blur" },
        // ],
        // sort: [
        //   { required: true, message: "显示顺序不能为空", trigger: "blur" },
        // ],
        // status: [
        //   {
        //     required: true,
        //     message: "文件夹状态（0正常 1停用）不能为空",
        //     trigger: "blur",
        //   },
        // ],
        // tenantId: [
        //   { required: true, message: "租户编号不能为空", trigger: "blur" },
        // ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;    
      // 处理查询参数
      let params = { ...this.queryParams };
      this.addBeginAndEndTime(
        params,
        this.dateRangeFolderCreateTime,
        "folderCreateTime"
      );
      this.addBeginAndEndTime(
        params,
        this.dateRangeFolderLastTime,
        "folderLastTime"
      );
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, "createTime");
      // 执行查询
      // getXTbFolderPage(params).then((response) => {
      //   this.list = response.data.list;
      //   this.total = response.data.total;
      //   this.loading = false;
      // });
      listFolder(params).then(response => {
        // 这个 rootId 是字符串0，dep树的是数字 0
        this.list = this.customerHandleTree(response.data, "id","parentId","children","0");
        this.loading = false;
      });
    },
    /**
     * 用 level 最小的root当rootid
     * level 表示数的层级，
     */
    customerHandleTree(data, id, parentId, children, rootId) {
      id = id || 'id'
      parentId = parentId || 'parentId'
      children = children || 'children'
      rootId = rootId || Math.min.apply(Math, data.map(item => {
        return item[parentId]
      })) || 0

      // 删除 level字段
      var multipleRootId = rootId;
      // var minLevel = 0;
      // if(data.length > 0) minLevel = data[0][level];
      // var multipleRootId = "";
      // if(data.length > 0) {
      //   for (let index = 0; index < data.length; index++) {
      //     const element = data[index];
      //     var curLevel = element[level];
      //     var curRootId = element[parentId];
      //     if (curLevel === minLevel && multipleRootId.indexOf(curRootId) === -1) {
      //       multipleRootId += curRootId + ",";
      //     }
      //     // 有几棵树就判断几遍，不需要遍历所有元素
      //     if (curLevel !== minLevel)  break;
      //   }
      // }

      //对源数据深度克隆
      const cloneData = JSON.parse(JSON.stringify(data))
      //循环所有项
      // 虚拟根项，不存在于数据库，不显示在列表上，且只有一个根项，就像一颗树的根节点，id 默认为0
      // 过滤出当前项(虚拟根项，id = 0)的所有子项，放到 treeData 中
      const treeData = cloneData.filter(father => {
        // 过滤出当前项的所有子项，放到 branchArr 中
        let branchArr = cloneData.filter(child => {
          //返回每一项的子级数组
          return father[id] === child[parentId]
        });
        branchArr.length > 0 ? father.children = branchArr : '';
        //返回第一层
        // return father[parentId] === rootId;
        // 多个不同父级id的树
        return multipleRootId.indexOf(father[parentId]) !== -1;
      });
      return treeData !== '' ? treeData : data;
    },
    /** 转换数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        parentId: undefined,
        sort: undefined,
        ownerUserId: undefined,
        status: undefined,
        folderCreateTime: undefined,
        folderLastTime: undefined,
        tenantId: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
      // 搜索的时候展开搜索结果树
      this.refreshTable = false;
      this.isExpandAll = true;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeFolderCreateTime = [];
      this.dateRangeFolderLastTime = [];
      this.dateRangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文件夹";
      listFolder().then(response => {
	        this.folderOptions = this.handleTree(response.data, "id","parentId","children","0");
      });
      if (this.form.id === undefined) {
        this.form.fileType = "xmind";
        let nowDateStr = getNowDate();
        this.form.folderCreateTime =  nowDateStr;
        this.form.folderLastTime =  nowDateStr;
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getXTbFolder(id).then((response) => {
        this.form = response.data;
        if (this.form.parentId === '0') { // 无父级时，标记为 undefined，避免展示为 Unknown
          this.form.parentId = undefined;
        }
        this.open = true;
        this.title = "修改文件夹";
      });
      listFolder(row.id).then(response => {
	        this.folderOptions = this.handleTree(response.data, "id","parentId","children","0");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateXTbFolder(this.form).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createXTbFolder(this.form).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal
        .confirm('是否确认删除文件夹编号为"' + id + '"的数据项?')
        .then(function () {
          return deleteXTbFolder(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = { ...this.queryParams };
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.addBeginAndEndTime(
        params,
        this.dateRangeFolderCreateTime,
        "folderCreateTime"
      );
      this.addBeginAndEndTime(
        params,
        this.dateRangeFolderLastTime,
        "folderLastTime"
      );
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, "createTime");
      // 执行导出
      this.$modal
        .confirm("是否确认导出所有文件夹数据项?")
        .then(() => {
          this.exportLoading = true;
          return exportXTbFolderExcel(params);
        })
        .then((response) => {
          this.$download.excel(response, "${table.classComment}.xls");
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
  },
};
</script>
